package com.wondream.myframework.app.common.excel.processor;

import com.wondream.myframework.app.common.constant.Constants;
import com.wondream.myframework.app.common.excel.context.CfssPoiExporterContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 默认的行处理器。单元格内容中含有${key}的进行替换，否则不处理
 */
@Slf4j
public class DefaultRowProcessor implements RowProcessor {

    public static class SINGLE {
        public static DefaultRowProcessor INSTANCE = new DefaultRowProcessor();
    }

    @Override
    public int dealRow(XSSFRow currentRow, CfssPoiExporterContext peContext) {
        for (int i = 0; i < currentRow.getLastCellNum(); i++) {
            XSSFCell cell = currentRow.getCell(i);
            if (null == cell || CellType.STRING != cell.getCellType()) {
                continue;
            }
            String cellContent = cell.getStringCellValue();
            String resolveContent = resolve(cellContent, peContext);
            cell.setCellValue(resolveContent);
        }
        return 1;
    }

    /**
     * 将带有${key}和${vo.key}的内容进行替换
     */
    public static String resolve(String cellContent, CfssPoiExporterContext peContext) {
        String resolvedContent = cellContent;
        Pattern pattern = Pattern.compile(Constants.POI_KEY_REGEXP2);
        boolean needDeal = false;
        // 处理${key}
        for (Matcher matcher = pattern.matcher(resolvedContent); matcher.find(); matcher = pattern.matcher(resolvedContent)) {
//            String key = matcher.group(1);
//            String value = (String) peContext.getRootObjectMap().get(key);
//            resolvedContent = matcher.replaceFirst("$2");
            peContext.EVAL_CONTEXT.setVariables(peContext.getRootObjectMap());
            String expression = matcher.replaceFirst("#$2");
//            peContext.getSpelExpressionParser().parseExpression(expression).getValue(peContext.EVAL_CONTEXT, String.class);
            resolvedContent = expression; //替换内容
            needDeal = true;
        }
        // 处理${vo.key}
        pattern = Pattern.compile(Constants.POI_VO_DOT_KEY_REGEXP2);
        String vo = null;
        try {
            for (Matcher matcher = pattern.matcher(resolvedContent); matcher.find(); matcher = pattern.matcher(resolvedContent)) {
                vo = matcher.group(2);
                vo = vo.substring(0, vo.length() - 1);
                Object rootObjectItem = peContext.getRootObjectMap().get(vo);
                peContext.EVAL_CONTEXT.setVariable(vo, rootObjectItem);
                String expression = matcher.replaceFirst("#$2$3"); //转换成EL
                resolvedContent = expression;
                needDeal = true;
            }
        } catch (Exception e) {
            log.warn("EL解析出错，或不存在.expression:" + vo);
            resolvedContent = "";
        }
        if (needDeal) {
            resolvedContent = peContext.getSpelExpressionParser().parseExpression(resolvedContent).getValue(peContext.EVAL_CONTEXT, String.class);
        }
        return resolvedContent;
    }

    @Override
    public int support(XSSFRow row) {
        return 0;
    }

    /**
     * 将带有${key}和${vo.key}的内容进行替换
     */
    public static String resolveItem(String cellContent, int index, String foreachKey, CfssPoiExporterContext peContext) {
        String resolvedContent = cellContent;

        boolean needDeal = false;
        // 处理${cfssItem.key}
        Pattern pattern = Pattern.compile(Constants.POI_ITEM_KEY_REGEXP);
        try {
            for (Matcher matcher = pattern.matcher(resolvedContent); matcher.find(); matcher = pattern.matcher(resolvedContent)) {
                String expression = matcher.replaceFirst("#" + foreachKey + "[" + index + "].$3"); //转换成EL
                resolvedContent = expression; //替换内容
                needDeal = true;
            }
        } catch (Exception e) {
            log.warn("EL解析出错，或不存在.expression:" + cellContent);
            resolvedContent = "";
        }

        // 处理${vo.key}
        String content = null;
        pattern = Pattern.compile(Constants.POI_VO_DOT_KEY_REGEXP2);
        try {
            Matcher matcher = pattern.matcher(resolvedContent);
            for (; matcher.find(); matcher = pattern.matcher(resolvedContent)) {
                content = matcher.group(2).substring(0, content.length() - 1);
                Object value = peContext.getRootObjectMap().get(content);
                peContext.EVAL_CONTEXT.setVariable(content, value);
                resolvedContent = matcher.replaceFirst("#$2$3"); //转换成EL
                needDeal = true;
            }
        } catch (Exception e) {
            log.warn("EL解析出错，或不存在.expression:" + content);
            resolvedContent = "";
        }

        pattern = Pattern.compile(Constants.POI_KEY_REGEXP2);
        // 处理${key}
        for (Matcher matcher = pattern.matcher(resolvedContent); matcher.find(); matcher = pattern.matcher(resolvedContent)) {
            peContext.EVAL_CONTEXT.setVariables(peContext.getRootObjectMap());
            resolvedContent = matcher.replaceFirst("#$2"); //替换内容
            needDeal = true;
        }

        if (needDeal) {
            resolvedContent = peContext.getSpelExpressionParser().parseExpression(resolvedContent).getValue(peContext.EVAL_CONTEXT, String.class);
        }
        return resolvedContent;
    }

}
